package com.msf.tutorial.java8.chapter7;

import java.util.*;

/**
 * 使用流
 */
public class C01Use {

    /**
     * 筛选和切片
     * filter
     */
    public static void filterStream() {
        List<Integer> list = Arrays.asList(1, 2, 1, 3, 3, 2, 4);
        list.stream()
            .filter(i -> i % 2 == 0)
            .forEach(System.out::println);  // 2,2,4
    }

    /**
     * 筛选和切片
     * distinct
     */
    public static void distinctStream() {
        List<Integer> list = Arrays.asList(1, 2, 1, 3, 3, 2, 4);
        list.stream()
            .filter(i -> i % 2 == 0)
            .distinct()
            .forEach(System.out::println);  // 2,4
    }

    /**
     * 截断流
     * limit
     */
    public static void limitStream() {
        List<Integer> list = Arrays.asList(1, 2, 1, 3, 3, 2, 4);
        list.stream()
            .filter(i -> i % 2 == 0)
            .limit(1)
            .forEach(System.out::println);  // 2
    }

    /**
     * 跳过元素
     * skip
     */
    public static void skipStream() {
        List<Integer> list = Arrays.asList(1, 2, 1, 3, 3, 2, 4);
        list.stream()
            .filter(i -> i % 2 == 0)
            .skip(2)
            .forEach(System.out::println);  // 4
    }

    /**
     * 映射
     * map
     */
    public static void mapStream() {
        List<String> list = Arrays.asList("Java 8", "Lambdas", "In", "Action");
        list.stream()
            .map(String::length)
            .forEach(System.out::println);  // 6,7,2,6
    }

    public static void main(String[] args) {
        System.out.println("========= filter ===========");
        filterStream();

        System.out.println("=========== distinct ===========");
        distinctStream();

        System.out.println("=========== limit ===========");
        limitStream();

        System.out.println("=========== skip ===========");
        skipStream();

        System.out.println("=========== map ===========");
        mapStream();
    }

}
